#!/usr/bin/php
<?php

function getDirSize($dir)
{
    if (!is_dir($dir)) {
        return filesize($dir);
    }
    $dp = opendir($dir);
    if (!$dp) {
        fprintf(STDERR, "%s 目录打开失败!\n", $dir);
        return 0;
    }

    $size = 0;
    while (($file = readdir($dp)) != FALSE) {
        if ($file === "." || $file === "..")
            continue;
        $path = $dir.DIRECTORY_SEPARATOR.$file;
        if (is_dir($path))
            $size += getDirSize($path);
        else
            $size += filesize($path);
    }

    closedir($dp);

    return $size;
}

function preSize($size)
{
    for ($count = 0; $size > 1024; $size /= 1024) {
        $count++;
    }
    return sprintf("%.1f%s", $size, "BKMGTP"[$count]);
}

function main($argc, & $argv)
{
    if ($argc < 2) {
        $dir = ".";
    } else {
        $dir = $argv[1];
    }

    printf("%s: %s\n", $dir, preSize(getDirSize($dir)));

    return 0;
}

exit(main($argc, $argv));

